package org.makcro.sms.services.chat.web.client.mvc;

import java.util.List;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.mvc.view.AgentsMessagesView;
import org.makcro.sms.services.chat.web.client.services.message.MessageServiceAsync;
import org.makcro.sms.services.chat.web.shared.dto.HistoryItemDto;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class AgentsMessagesController extends Controller {

	private AgentsMessagesView	view;
	private MessageServiceAsync	messageServiceAsync;
	private Timer				timer;

	public AgentsMessagesController() {
		registerEventTypes( AppEvents.LoginSuccessful );
		registerEventTypes( AppEvents.ANSWER_SENT );
	}

	@Override
	protected void initialize() {
		super.initialize();
		view = new AgentsMessagesView( this );
		messageServiceAsync = Registry.get( Constants.Services.MessageService );
		//initTimer();
	}

	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if ( type == AppEvents.LoginSuccessful ) {
			onLoginSuccessful( event );
			onUpdateData();
		}
		else if (type == AppEvents.ANSWER_SENT) {
			onUpdateData();
		}
	}

	private void onLoginSuccessful(AppEvent event) {
		forwardToView( view, event );
	}

	public void initTimer() {
		timer = new Timer() {
			
			@Override
			public void run() {
				
				onUpdateData();
			}
		};
		timer.scheduleRepeating( 30 * 1000 );
	}

	protected void onUpdateData() {
		messageServiceAsync.getCurrentAgentsMessages( new AsyncCallback<List<HistoryItemDto>>() {
			
			@Override
			public void onSuccess(List<HistoryItemDto> result) {
				AppEvent event = new AppEvent( AppEvents.AGENT_MESSAGES_UPDATE, result );
				forwardToView( view, event );
			}
			
			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);
				
			}
		} );
		
	}

}
